<template>
  <div class="canvas-recorder" :style="`width:${width}px;min-height:${height}px;`">
    <video v-if="!isRecording && videoUrl" :width="width" :height="height" controls="true" autoplay="true" id="video"
      :src="videoUrl"></video>
    <div class="f-r-a-c ctrls">
      <button v-show="isRecording" class="btn" @click="stopRecord">停止</button>
      <div class="f-r-a-c" v-show="!isRecording">
        <button class="btn" @click="startRecord">
          录制生成过程
        </button>

        <button v-show="videoUrl" class="btn" @click="saveRecord">
          下载
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from "vue";
export default {
  name: "CanvasRecorder",
  components: {},
  props: {
    canvasId: String,
    width: Number | String,
    height: Number | String,
  },
  setup(props, context) {
    const { canvasId } = props;
    const mimeTypeMp4 = "video/mp4";
    const mimeTypeWebm = "video/webm";
    const isSupportMp4 = MediaRecorder.isTypeSupported(mimeTypeMp4)
    let recorder = null;
    let videoUrl = ref("");
    let isRecording = ref(false);
    const startRecord = () => {
      videoUrl.value = "";
      const canvas = document.getElementById(canvasId);
      const stream = canvas.captureStream(30);

      let mimeType = mimeTypeMp4;
      if (!isSupportMp4) {
        mimeType = mimeTypeWebm;
      }
      recorder = new MediaRecorder(stream, { mimeType });

      const chunks = [];
      recorder.ondataavailable = function (event) {
        if (event.data) {
          chunks.push(event.data);
        }
      };

      recorder.onstop = () => {
        const videoBlob = new Blob(chunks, { type: mimeType }); // 创建视频文件
        const url = URL.createObjectURL(videoBlob);
        videoUrl.value = url;
      };

      recorder.start();
      isRecording.value = true;
    };

    const stopRecord = () => {
      recorder.stop();
      isRecording.value = false;
    };

    const saveRecord = () => {
      let url = videoUrl.value;
      if (isSupportMp4) {
        saveMp4(url);
      } else {
        saveWebm(url);
      }
    }

    const saveMp4 = (url) => {
      var tag = document.createElement("a");
      tag.href = url;
      tag.download = `canvas_recorder_${+new Date()}.mp4`;
      document.body.appendChild(tag);
      tag.click();
      document.body.removeChild(tag);
    };

    // webm->mp4 转换链接 https://convertio.co/zh/download/c6718cb93ff39a6fbac2e53d7add591d41fa96/
    const saveWebm = (url) => {
      var tag = document.createElement("a");
      tag.href = url;
      tag.download = `canvas_recorder_${+new Date()}.webm`;
      document.body.appendChild(tag);
      tag.click();
      document.body.removeChild(tag);
    };

    return { videoUrl, isRecording, startRecord, stopRecord, saveRecord };
  },
};
</script>
<style lang="less" scoped>
.canvas-recorder {
  border-radius: 8px;
  position: relative;
  border: dashed 1px #ccc;

  .ctrls {
    margin: 10px 0;
  }
}
</style>